import { NextRequest, NextResponse } from 'next/server';
import { Server as SocketIOServer } from 'socket.io';
import { auth } from '@/auth';
import { ClientToServerEvents, ServerToClientEvents, InterServerEvents, SocketData } from '@/types/socket';

// 全局Socket.io服务器实例
let io: SocketIOServer<ClientToServerEvents, ServerToClientEvents, InterServerEvents, SocketData> | null = null;

/**
 * 处理Socket.io连接请求
 */
export async function GET(req: NextRequest) {
  try {
    // 如果Socket.io服务器已初始化，直接返回成功
    if (io) {
      return NextResponse.json(
        { 
          success: true, 
          message: 'Socket.io服务器已就绪'
        },
        { status: 200 }
      );
    }

    // 获取用户会话信息
    const session = await auth();
    if (!session || !session.user) {
      return NextResponse.json(
        { 
          success: false, 
          message: '未授权访问', 
          error: 'Unauthorized'
        },
        { status: 401 }
      );
    }

    // 创建Socket.io服务器
    // 注意：在Next.js App Router中，我们需要使用Edge Runtime或外部服务来实现完整的WebSocket支持
    // 这里提供一个基本实现，实际生产环境可能需要使用专用的WebSocket服务
    const { Server } = await import('socket.io');
    
    // 创建Socket.io服务器实例
    io = new Server({
      path: '/api/socket',
      addTrailingSlash: false,
      cors: {
        origin: process.env.NEXT_PUBLIC_APP_URL || '*',
        methods: ['GET', 'POST'],
        credentials: true
      },
      connectionStateRecovery: {
        // 启用连接状态恢复
        maxDisconnectionDuration: 2 * 60 * 1000, // 2分钟
        skipMiddlewares: true,
      },
      allowEIO3: true, // 允许Engine.IO v3客户端连接
      pingTimeout: 60000, // 增加ping超时时间
      pingInterval: 25000, // ping间隔保持不变
      connectTimeout: 45000, // 增加连接超时时间
      transports: ['polling', 'websocket'], // 确保支持轮询和WebSocket
    });

    // 处理连接事件
    io.on('connection', (socket) => {
      console.log('Socket连接成功:', socket.id);
      
      // 设置Socket数据
      const userData: SocketData = {
        userId: session.user.id || 'unknown',
        userName: session.user.name || 'Anonymous',
        userImage: session.user.image || undefined,
        connectedAt: new Date(),
        currentProjects: [],
        currentTasks: [],
      };
      
      // 将用户数据附加到socket
      socket.data = userData;
      
      // 发送连接状态
      socket.emit('connection-state', {
        status: 'connected',
        lastConnected: Date.now()
      });
      
      // 处理加入项目
      socket.on('join-project', (projectId) => {
        console.log(`用户 ${userData.userName} 加入项目: ${projectId}`);
        socket.join(`project:${projectId}`);
        socket.data.currentProjects.push(projectId);
        
        // 通知项目其他成员
        socket.to(`project:${projectId}`).emit('member-joined', {
          projectId,
          user: {
            id: userData.userId,
            name: userData.userName,
            image: userData.userImage
          },
          timestamp: Date.now()
        });
      });
      
      // 处理加入任务
      socket.on('join-task', (taskId) => {
        console.log(`用户 ${userData.userName} 加入任务: ${taskId}`);
        socket.join(`task:${taskId}`);
        socket.data.currentTasks.push(taskId);
      });
      
      // 处理任务更新
      socket.on('task-update', (data) => {
        console.log(`任务更新: ${data.taskId}`);
        // 广播给项目成员
        io?.to(`project:${data.projectId}`).emit('task-updated', data);
      });
      
      // 处理新评论
      socket.on('new-comment', (data) => {
        if (data.taskId) {
          console.log(`任务评论: ${data.taskId}`);
          io?.to(`task:${data.taskId}`).emit('new-comment-added', data);
        } else if (data.docId) {
          console.log(`文档评论: ${data.docId}`);
          // 广播评论给项目成员
          socket.to(`project:${data.projectId}`).emit('comment-added', {
            projectId: data.projectId,
            docId: data.docId,
            comment: data.comment
          });
        }
      });
      
      // 处理文档更新
      socket.on('doc-update', (data) => {
        console.log(`文档更新: ${data.docId}`);
        // 广播文档更新给项目成员
        socket.to(`project:${data.projectId}`).emit('doc-updated', {
          projectId: data.projectId,
          docId: data.docId,
          update: data.update,
          updatedBy: data.updatedBy,
          timestamp: data.timestamp || Date.now()
        });
      });
      
      // 处理光标移动
      socket.on('cursor-move', (data) => {
        // 发送给同一文档的其他用户
        socket.to(`project:${data.projectId}`).emit('cursor-moved', {
          projectId: data.projectId,
          docId: data.docId,
          userId: data.userId,
          userName: data.userName,
          userColor: data.userColor,
          position: data.position,
          timestamp: data.timestamp || Date.now()
        });
      });
      
      // 处理用户状态
      socket.on('user-status', (status) => {
        const statusData = {
          userId: userData.userId,
          userName: userData.userName,
          status,
          lastActive: Date.now()
        };
        
        // 广播给用户所在的所有项目
        userData.currentProjects.forEach(projectId => {
          socket.to(`project:${projectId}`).emit('user-status-changed', statusData);
        });
      });
      
      // 处理开始输入
      socket.on('typing-start', (data) => {
        if (data.taskId) {
          socket.to(`task:${data.taskId}`).emit('user-typing', data);
        } else if (data.docId) {
          socket.to(`project:${data.projectId}`).emit('user-typing', data);
        }
      });
      
      // 处理结束输入
      socket.on('typing-end', (data) => {
        if (data.taskId) {
          socket.to(`task:${data.taskId}`).emit('user-stopped-typing', data);
        } else if (data.docId) {
          socket.to(`project:${data.projectId}`).emit('user-stopped-typing', data);
        }
      });
      
      // 处理ping请求
      socket.on('ping', (callback) => {
        const serverTime = Date.now();
        callback(serverTime);
      });
      
      // 处理断开连接
      socket.on('disconnect', (reason) => {
        console.log(`Socket断开连接: ${socket.id}, 原因: ${reason}`);
        
        // 通知用户所在的所有项目
        userData.currentProjects.forEach(projectId => {
          socket.to(`project:${projectId}`).emit('user-status-changed', {
            userId: userData.userId,
            userName: userData.userName,
            status: 'offline',
            lastActive: Date.now()
          });
          
          // 通知项目其他成员
          socket.to(`project:${projectId}`).emit('member-left', {
            projectId,
            user: {
              id: userData.userId,
              name: userData.userName,
              image: userData.userImage
            },
            timestamp: Date.now()
          });
        });
      });
    });

    console.log('Socket.io服务器初始化成功');
    
    return NextResponse.json(
      { 
        success: true, 
        message: 'Socket.io服务器初始化成功'
      },
      { status: 200 }
    );
  } catch (error: any) {
    console.error('Socket.io服务器初始化失败:', error);
    return NextResponse.json(
      { 
        success: false, 
        message: 'Socket.io服务器初始化失败', 
        error: error.message || String(error)
      },
      { status: 500 }
    );
  }
} 